#!/usr/bin/python
import sys
import os
import os.path
import re
import array
#from hb.common.utils import hb_info

USAGE = """img2c - Embed a image in a C header file (like XPM)
Usage: img2c [file ..] Convert all the file <file.img> to <file.h>"""

if len(sys.argv) < 3:
    print(USAGE)
    sys.exit(1)

#r = re.compile("^([a-zA-Z._][a-zA-Z._0-9]*)[.][iI][mM][gG]$")
r = re.compile("^([a-zA-Z._][a-zA-Z._0-9]*)[.][bB][iI][nN]$")

def img_2_c_array():
    path = sys.argv[1]
    output_c_array_path = sys.argv[2]

    filename = os.path.basename(path)
    #hb_info(f'img {path} is transfered to c array file {output_c_array_path}')
    m = r.match(filename)
    # Allow only filenames that make sense
    # as C variable names
    if not(m):
        # print("Skipped file (unsuitable filename): " + filename)
        #hb_info(f'Skipped file (unsuitable filename): {filename}')
        return

    # Read image file as character array
    bytes = array.array('B', open(path, "rb").read())
    count = len(bytes)

    # Create the C header
    text = "/* %s - %d bytes */\n" \
        "static const unsigned char %s_img[] __attribute__ ((aligned (32))) = {\n" % (filename, count, m.group(1))

    # Iterate the characters, we want
    # lines like:
    #   0x01, 0x02, .... (16 values per line maximum)
    i = 0
    count = len(bytes)
    for byte in bytes:
        # Every new line starts with two whitespaces
        if (i % 16) == 0:
            text += "  "
        # Then the hex data (up to 16 values per line)
        text += "0x%02x" % (byte)
        # Separate all but the last values
        if (i + 1) < count:
            text += ", "
        if (i % 16) == 15:
            text += '\n'
        i += 1

    # Now conclude the C source
    text += "};\n/* End Of File */\n"

    # open(os.path.splitext(path)[0] + ".h", 'w').write(text)
    open(output_c_array_path, 'w').write(text)


img_2_c_array()
